﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Net.Mail;

public partial class SendDailyAppnts : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            // Get today's appointments.
            List<CalendarEvent> lstEvents = EventDAO.getEventsByDate(DateTime.Now.Date);
            ArrayList mailsList = new ArrayList();

            foreach (CalendarEvent cevent in lstEvents)
            {
                for (int i = 0; i < cevent.users.Length; i++)
                {
                    User u = EventDAO.getUserByName(cevent.users[i]);
                    if (u != null)
                    {
                        mailsList.Add(u.emailId);
                    }
                }
                try
                {
                    // Construct email messages & Send emails.
                    SendEmail(mailsList, cevent);
                }
                catch (Exception ex)
                {

                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private static void SendEmail(ArrayList mailsList, CalendarEvent cevent)
    {
        MailMessage mailMessage = new MailMessage();
        SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
        smtpClient.EnableSsl = true;
        smtpClient.Credentials = new System.Net.NetworkCredential("organizerwork@gmail.com", "Rizwan@123"); // User id and password.
        mailMessage.From = new MailAddress("organizerwork@gmail.com");
        for (int i = 0; i < mailsList.Count; i++)
        {
            mailMessage.To.Add(new MailAddress("organizerwork@gmail.com"));
            mailMessage.To.Add(new MailAddress(mailsList[i].ToString()));
        }
        string users = String.Join(",", cevent.users);
        mailMessage.ReplyTo = new MailAddress("organizerwork@gmail.com");
        mailMessage.Subject = "Your appointment details";
        mailMessage.Body = "Your appointment details are as follows.\n\n Title : " + cevent.title + "\n Description : " + cevent.description +
            "\n Group Name : " + cevent.groupname + "\n Company : " + cevent.companyname + "\n Users : " + users + "\n Start time : " + cevent.start + "\n End time : " + cevent.end + " \n\nRegards \n admin.";
        smtpClient.Send(mailMessage);
    }
}
